package com.project.controller;

import com.project.common.Result;
import com.project.dto.AuthDTO;
import com.project.redis.RedisCache;
import com.project.redis.RedisKey;
import com.project.service.UserDbService;
import com.project.utils.JwtUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Set;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 权限相关
 * @Date: 2024-04-29-19:48
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@Api(tags = "权限相关接口")
public class AuthController {

    @Resource
    private UserDbService userDbService;

    @Resource
    private RedisCache redisCache;

    @RequestMapping(value = "/gen/token", method = RequestMethod.POST)
    @PreAuthorize("hasAnyRole('USER')")
    public Result<?> genDbAuthToken(@Validated @RequestBody AuthDTO auth, @RequestHeader("Authentication") String AuthToken) {

        log.info("开始生成鉴权 token, id: {}, ttl: {}", auth.getId(), auth.getTtl());
        String userId = JwtUtil.getUserIdByAuthentication(AuthToken);
        // 从redis获取
        String cacheKey = RedisKey.USER_DB_TABLES_LIST + userId;
        Set<Long> cacheSet = redisCache.getCacheSet(cacheKey);
        if (!cacheSet.contains(auth.getId())) {
            return Result.error("您不具备操作该数据库的权限");
        }
        return userDbService.genDbAuthToken(auth, userId);
    }

}
